import { generateUUID } from '@pier88health/p8h-common'
import { RouteSceneKey } from '@NAVIGATION/scenes'
import Taro from '@tarojs/taro'
import { Analytic_Type } from '@CONSTANTS/analytic'
import { openPage, showToast } from '@UTILS/common'
import { EventsITF } from '@INTERFACES/Events'
import api from '@API'
import { PlanManagementITF } from '@INTERFACES/PlanManagement'
import { DECISION_TYPE } from '@CONSTANTS/decision'
import Navigate from '@NAVIGATION/navigateManager'

export const getCustomBtnInfo = async (data: EventsITF) => {
  const info = { HasPainManagement: false, HasDecisionResult: false, p8Id: '', Success: false }
  try {
    const { RouteType, RouteData } = data
    const result: PlanManagementITF = await api.getMyPainManagement({})
    const isDecision = [RouteSceneKey.decisionFlowIndex, RouteSceneKey.decisionFlow].includes(RouteType)
    if (result?.HasPainManagement) {
      info.HasPainManagement = true
      info.Success = true
      return info
    }
    if (isDecision) {
      const isSurvey = RouteData?.type === DECISION_TYPE.Survey
      const dId = RouteData?.dId
      let lastResult = null
      if (isSurvey) {
        lastResult = await api.getMyLastSurveyByTemplate({ tId: dId })
      } else {
        lastResult = await api.getMyLastJourneyByDecisionFlowId({ dfId: dId })
      }
      info.Success = true
      if (lastResult && lastResult?.p8Id) {
        info.HasDecisionResult = true
        info.p8Id = lastResult?.p8Id
        return info
      }
    }
    return info
  } catch (e) {
    showToast(e)
  }
  return info
}
export const onClickCustomBtn = async (data: EventsITF, eventObj: unknown): Promise<void> => {
  const requestId = generateUUID()
  const { RouteType, RouteData } = data
  const sceneData = { Scene: RouteSceneKey.homePage, RequestId: requestId }
  Object.assign(RouteData, { requestId })
  const { HasPainManagement, HasDecisionResult, p8Id, Success } = await getCustomBtnInfo(data)
  eventObj && Taro.tracker.trackEvent(Analytic_Type.tap_customized_plan.eventId, eventObj, sceneData)
  if (!Success || HasPainManagement) return
  if (HasDecisionResult) {
    const isSurvey = RouteData?.type === DECISION_TYPE.Survey
    Navigate.decisionResultPage({
      id: p8Id, isSurvey: `${isSurvey}`, requestId
    })
    return
  }
  openPage(RouteType, RouteData)
}
